package jEDF.JEDF;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

import javax.swing.*;

import jEDF.EDF.*;

/**
 *
 * <p>Titre : jEDF</p>
 * <p>Description : Java European Data Format Viewer and Analyser</p>
 * <p>Author : Nizar Kerkeni</p>
 * <p>Copyright : Copyright (c) 2003-2006</p>
 * <p>Version : 2.0</p>
 */
public class JEDFSignalCaption extends JPanel {

    private Polysomnograph polysomnograph = null;
    private boolean drawUnits = true;
    private boolean drawLabel = true;

    /**
     * @param polysomnograph the corresponding polysomnograph
     */
    public JEDFSignalCaption(Polysomnograph polysomnograph) {
        this.polysomnograph = polysomnograph;
        polysomnograph.setSignalCaption(this);

        Color backgroundColor = Color.WHITE;

        setBackground(backgroundColor);

        addMouseMotionListener(new MouseMotionAdapter() {

            public void mouseMoved(MouseEvent arg0) {
                processMouseMove(arg0);
            }
        });

        addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent arg0) {
                if (SwingUtilities.isRightMouseButton(arg0)) {
                    processMouseClick(arg0);
                }
            }
        });
    }

    private void processMouseMove(MouseEvent me) {
        JEDFGraph graph = getCorrespondingGraph(me);

        if (graph == null) {
            return;
        }

        EDFSignal signal = graph.getSignal();

        if (signal != null) {
            setToolTipText(signal.getLabel());
        }
        //setToolTipText(signal.toTooltipString());
    }

    private void processMouseClick(MouseEvent me) {
        final JEDFGraph graph = getCorrespondingGraph(me);

        if (graph == null) {
            return;
        }

        final EDFSignal signal = graph.getSignal();

        final JPopupMenu jPopupMenu = new JPopupMenu();

        JButton jmiIncrease = new JButton(JEDFMainWindow.getLocalizedString(
                "Increase size"));
        JButton jmiDecrease = new JButton(JEDFMainWindow.getLocalizedString(
                "Decrease size"));
        JButton jmiReset = new JButton(JEDFMainWindow.getLocalizedString(
                "Reset size"));

        final JCheckBox jcbReverse = new JCheckBox(JEDFMainWindow.getLocalizedString("Reverse"));
        final JLabel jlTitle = new JLabel(signal.getLabel() + "  (X " +
                graph.getZoomFactor() + " )");

        jcbReverse.setSelected(graph.isInverted());

        jmiIncrease.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                graph.increaseVerticalSize();
                jlTitle.setText(signal.getLabel() + "  (X " +
                        graph.getZoomFactor() + " )");
            }
        });

        jmiDecrease.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                graph.decreaseVerticalSize();
                jlTitle.setText(signal.getLabel() + "  (X " +
                        graph.getZoomFactor() + " )");
            }
        });

        jmiReset.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                graph.resetVerticalSize();
                jlTitle.setText(signal.getLabel() + "  (X " +
                        graph.getZoomFactor() + " )");
            }
        });

        jcbReverse.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                graph.setInverted(jcbReverse.isSelected());
            }
        });

        //Graph graph = getCorrespondingGraph(me);



        jPopupMenu.setLayout(new GridLayout(0, 1));
        jPopupMenu.add(jlTitle);
        //jPopupMenu.addSeparator();
        jPopupMenu.add(jmiIncrease);
        jPopupMenu.add(jmiReset);
        jPopupMenu.add(jmiDecrease);
        //jPopupMenu.addSeparator();
        jPopupMenu.add(jcbReverse);

        jPopupMenu.show(this, me.getX(), me.getY());
    }

    private JEDFGraph getCorrespondingGraph(MouseEvent me) {
        JEDFGraph[] tabGraphs = polysomnograph.getAllGraphs();

        if (tabGraphs.length == 0) {
            return null;
        }

        float y = me.getY();
        y /= polysomnograph.getGraphHeight();

        if (y >= tabGraphs.length) {
            return null;
        }

        return tabGraphs[(int) y];
    }

    /* (non-Javadoc)
     * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
     */
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2D = (Graphics2D) g;
        display(g2D);
    }

    private void display(Graphics2D g) {
        JEDFGraph[] tabGraphs = polysomnograph.getAllGraphs();

        if (tabGraphs == null) {
            return;
        }

        float totalHeight = 0;

        for (int i = 0; i < tabGraphs.length; i++) {
            drawCaption(g, tabGraphs[i], (int) totalHeight);
//            drawXLimit(g, totalHeight, polysomnograph.getGraphHeight(), tabGraphs[i]);
            totalHeight += polysomnograph.getGraphHeight(); //tabGraphs[i].getHeight();
        }
    }

    private void drawCaption(Graphics2D g, JEDFGraph graph, float yOffset) {

        EDFSignal signal = graph.getSignal();

        String unit = signal.getPhysDim();
        String maxValue = "" + (float) signal.getPhysMax() / graph.getHeightMultiplier();
        String minValue = "" + (float) signal.getPhysMin() / graph.getHeightMultiplier();

        String maxCaption = (maxValue + " " + unit).trim();
        String minCaption = (minValue + " " + unit).trim();

        String label = signal.getLabel();

        FontMetrics fontMetrics = g.getFontMetrics();
        Rectangle2D rect = null;

        Insets insets = getInsets();
        float currentWidth = getWidth() - insets.left - insets.right;

        if (drawUnits) {
            Color currentColor = g.getColor();
            g.setColor(Color.LIGHT_GRAY);
            rect = fontMetrics.getStringBounds(maxCaption, g);
            if (!graph.isInverted()) {
                g.drawString(maxCaption, (int) (currentWidth - rect.getWidth()),
                        (int) (yOffset + rect.getHeight()));

                rect = fontMetrics.getStringBounds(minCaption, g);
                g.drawString(minCaption, (int) (currentWidth - rect.getWidth()),
                        (int) (yOffset + polysomnograph.getGraphHeight())); //graph.getHeight()));
                g.setColor(currentColor);
            } else {
                g.drawString(minCaption, (int) (currentWidth - rect.getWidth()),
                        (int) (yOffset + rect.getHeight()));

                rect = fontMetrics.getStringBounds(minCaption, g);
                g.drawString(maxCaption, (int) (currentWidth - rect.getWidth()),
                        (int) (yOffset + polysomnograph.getGraphHeight())); //graph.getHeight()));
                g.setColor(currentColor);
            }
        }

        if (drawLabel) {
            Font temp = g.getFont();
            g.setFont(new Font("georgia", Font.BOLD, 10));
            rect = fontMetrics.getStringBounds(label, g);
            g.drawString(label, (int) (this.getWidth() - rect.getWidth() - 10),
                    (int) (yOffset +
                    (rect.getHeight() +
                    polysomnograph.getGraphHeight()) /
                    2));
            g.setFont(temp);
        }

    }
}
